package com.tju.hotel.hotel.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.tju.hotel.R;
import com.tju.hotel.hotel.MyApplication;
import com.tju.hotel.hotel.bean.MemberBean;
import com.tju.hotel.hotel.util.DeviceUtils;
import com.tju.hotel.hotel.util.MD5Util;
import com.tju.hotel.hotel.util.OkHttpTool;
import com.tju.hotel.hotel.util.SPUtils;
import com.tju.hotel.hotel.util.ServiceUrls;
import com.tju.hotel.hotel.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class RegisterActivity extends AppCompatActivity {

    private Activity mActivityContext;
    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    private MyApplication myApplication;

    private EditText etPhone;//手机号
    private EditText etSmsCode;//验证码
    private EditText etName;//姓名
    private EditText etPassword;//密码
    private EditText etPasswordSure;//确认密码
    private RadioGroup rgSex;//性别
    private TextView tvSendSms;//文本-发送短信
    private TextView tvLogin;//文本 -登录
    private TextView tvForget;//文本-忘记密码
    private Button btnRegistert;

    //重写父类方法
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myApplication= (MyApplication) getApplication();
        mActivityContext=this;

        //设置页面布局
        setContentView(R.layout.activity_register);
        //获取控件
        etPhone = findViewById(R.id.et_register_phone);
        etSmsCode = findViewById(R.id.et_register_sms_code);
        etName = findViewById(R.id.et_register_name);
        etPassword = findViewById(R.id.et_register_password);
        etPasswordSure = findViewById(R.id.et_register_password_sure);
        rgSex = findViewById(R.id.rg_register_sex);
        tvSendSms = findViewById(R.id.tv_register_send_sms);
        tvLogin = findViewById(R.id.tv_register_login);
        tvForget = findViewById(R.id.tv_register_forget);
        btnRegistert = findViewById(R.id.btn_register);

        //设置控件事件
        setViewEventListener();
    }

    //设置控件事件y
    private void setViewEventListener() {
        //--发送验证码
        tvSendSms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取参数
                String phone=etPhone.getText()==null?"":etPhone.getText().toString();
                if (!Tools.isMobile(phone)){
                    etPhone.setError("请输入正确的手机号");
                    return;
                }
                //获取设备ID
                String deviceId= DeviceUtils.getDeviceUUID(RegisterActivity.this);
                //禁用发送按钮
                tvSendSms.setEnabled(false);

                //准备url
                String url= ServiceUrls.getMemberMethodUrl("sendSmsValid");
                //准备参数
                Map<String,Object> map=new HashMap<>();
                map.put("phone", phone);//手机号
                map.put("deviceId", deviceId);//设备UUID
                map.put("isRegister", true);//注册

                //发送网络请求
                OkHttpTool.httpPost(url, map, new OkHttpTool.ResponseCallback() {
                    @Override
                    public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                        RegisterActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (isSuccess && responseCode == 200) {
                                    //重新发送短信倒计时----Android自带倒计时类 倒计时60s，步长1s
                                    CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
                                        //每一步执行函数
                                        @Override
                                        public void onTick(long millisUntilFinished) {
                                            tvSendSms.setText(String.format(Locale.getDefault(), "重新获取(%1$d)", (millisUntilFinished / 1000)));
                                        }

                                        //完成执行函数
                                        @Override
                                        public void onFinish() {
                                            tvSendSms.setEnabled(true);//启用发送按钮
                                            tvSendSms.setText("获取验证码");
                                        }
                                    };
                                    timer.start();//启动定时器

                                    //解析服务端返回数据
                                    try {
                                        //json对象 获取code
                                        JSONObject jsonObject = new JSONObject(response);
                                        int code = jsonObject.getInt("code");
                                        if (code == 200) {
                                            //发送成功
                                            Toast.makeText(RegisterActivity.this, "验证码发送成功，请注意查收", Toast.LENGTH_LONG).show();
                                        } else {
                                            //发送失败 json.text中存放发送失败原因
                                            String text = jsonObject.getString("text");
                                            if (code == 404) {
                                                etPhone.setError(text);
                                            }
                                            Toast.makeText(RegisterActivity.this, text, Toast.LENGTH_LONG).show();
                                        }
                                        return;
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                Toast.makeText(RegisterActivity.this, "验证码发送失败，请稍后再试", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });
            }
        });
        //注册按钮
        //注册按钮
        btnRegistert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //=======获取注册表单数据
                String phone = etPhone.getText() == null ? "" : etPhone.getText().toString();//手机号
                String smsValidCode = etSmsCode.getText() == null ? "" : etSmsCode.getText().toString();//验证码
                String memberName = etName.getText() == null ? "" : etName.getText().toString();//会员姓名
                boolean sex = true;//默认男性
                //如果选择女性按钮，设置为女性
                if (rgSex.getCheckedRadioButtonId() == R.id.rb_register_sex_woman) {
                    sex = false;
                }
                String password = etPassword.getText() == null ? "" : etPassword.getText().toString();//密码
                String surePassword = etPasswordSure.getText() == null ? "" : etPasswordSure.getText().toString();//确认密码

                //======验证数据
                if (!Tools.isMobile(phone)) {
                    etPhone.setError("请填写正确的手机号");
                    return;
                }
                if (!Tools.isNotNull(smsValidCode)) {
                    etSmsCode.setError("请填写短信验证码");
                    return;
                }
                if (!Tools.isNotNull(memberName)) {
                    etName.setError("请填写您的姓名");
                    return;
                }
                if (!Tools.isNotNull(password) && password.length() < 8) {
                    etPassword.setError("密码强度不够");
                    return;
                }
                if (!password.equals(surePassword)) {
                    etPasswordSure.setError("两次密码不一致");
                    return;
                }

                //==========发送请求
                //拼接url
                String url = ServiceUrls.getMemberMethodUrl("register");
                //请求参数
                Map<String, Object> map = new HashMap<>();
                map.put("phone", phone);//手机号
                map.put("memberName", memberName);//姓名
                map.put("smsValidCode", smsValidCode);//验证码
                map.put("sex", sex);//性别
                map.put("password", MD5Util.getMD5(password));//密码 进行md5加密

                //发送请求
                OkHttpTool.httpPost(url, map, new OkHttpTool.ResponseCallback() {
                    @Override
                    public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                        RegisterActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String strText = "无法访问服务器，请稍后再试";//默认提示
                                if (isSuccess && responseCode==200) {
                                    try {
                                        //解析服务端返回
                                        JSONObject jsonObject = new JSONObject(response);
                                        int code = jsonObject.getInt("code");
                                        if (code == 200) {
                                            //成功返回
                                            //获取data中携带的用户信息数据-反序列化
                                            String strData = jsonObject.getString("data");
                                            MemberBean member = gson.fromJson(strData, MemberBean.class);
                                            if (member != null) {
                                                //将用户信息保存到Application中
                                                myApplication.setLoginMember(member);
                                                //将phone和password存入SharedPreferences
                                                SPUtils.put(mActivityContext, ServiceUrls.SP_MEMBER_PHONE, member.getPhone().trim());
                                                SPUtils.put(mActivityContext, ServiceUrls.SP_MEMBER_PASSWORD, member.getPassword().trim());
                                                strText = "注册成功";
                                                finish();//关闭Activity
                                            }
                                        } else {
                                            strText = jsonObject.getString("text");
                                        }

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                Toast.makeText(RegisterActivity.this, strText, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });
            }
        });
        //跳转到重置密码页面
        tvForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到重置密码页面
                Intent intent=new Intent(mActivityContext,ForgetPasswordActivity.class);
                startActivity(intent);
                finish();
            }
        });
        //跳转到重置密码页面
        tvForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到重置密码页面
                Intent intent=new Intent(mActivityContext,ForgetPasswordActivity.class);
                startActivity(intent);
                finish();
            }
        });

    }
}